from PIL import Image, ImageEnhance


def merge_images(image_paths, output_path):
    """
    合并 6 张图片为一个 2x3 的矩阵图片
    :param image_paths: 6 张图片的文件路径列表
    :param output_path: 合并后图片的保存路径
    """
    if len(image_paths) != 6:
        print("需要提供 6 张图片的路径。")
        return

    images = [Image.open(path) for path in image_paths]
    # 提高每张图片的清晰度
    sharpened_images = []
    sharpness_factor = 2.0  # 清晰度增强因子，可根据需要调整，大于 1 提高清晰度，小于 1 降低清晰度
    for img in images:
        enhancer = ImageEnhance.Sharpness(img)
        sharpened_img = enhancer.enhance(sharpness_factor)
        sharpened_images.append(sharpened_img)

    # 获取所有图片的宽度和高度
    widths, heights = zip(*(i.size for i in sharpened_images))
    # 找到最小的宽度和高度
    min_width = min(widths)
    min_height = min(heights)
    # 调整所有图片到最小尺寸
    resized_images = [img.resize((min_width, min_height)) for img in sharpened_images]

    rows = 2
    cols = 3
    total_width = cols * min_width
    total_height = rows * min_height

    merged_image = Image.new('RGB', (total_width, total_height))

    for i in range(rows):
        for j in range(cols):
            index = i * cols + j
            image = resized_images[index]
            x_offset = j * min_width
            y_offset = i * min_height
            merged_image.paste(image, (x_offset, y_offset))

    # 提高亮度
    enhancer = ImageEnhance.Brightness(merged_image)
    # 亮度增强因子，可根据需要调整，大于 1 提高亮度，小于 1 降低亮度
    brightness_factor = 1.5
    enhanced_image = enhancer.enhance(brightness_factor)

    enhanced_image.save(output_path)


    
if __name__ == "__main__":
    # 请替换为你实际的图片路径
    image_paths = [
        "0314A.jpg",
        "0314AC.jpg",
        "0314B.jpg",
        "0314BC.jpg",
        "0314C.jpg",
        "0314CC.jpg"
    ]
    output_path = "merged_image.jpg"
    merge_images(image_paths, output_path)

